package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * @author: zen
 * @date: 2020/4/12
 * @Title: EncodingFilter
 * @Description: 字符集转换过滤器
 */

@WebFilter(filterName = "Encoder",
            urlPatterns = "/test",
            initParams = @WebInitParam(name = "charset", value = "utf-8"))
public class EncodingFilter implements Filter {

    // 定义转换后的字符集
    private String newCharset;

    public void setNewCharset(String newCharset) {
        this.newCharset = newCharset;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 从过滤器的配置中获得初始化参数，如果没有就使用默认值
        if (filterConfig.getInitParameter("charset") != null) {
            setNewCharset(filterConfig.getInitParameter("charset"));
        } else {
            setNewCharset("utf-8");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 处理请求字符
        servletRequest.setCharacterEncoding(newCharset);
        // 传递给下一个过滤器，若没有则给相关Servlet
        filterChain.doFilter(servletRequest, servletResponse);
        // 处理响应字符集，若相关Servlet已有，则下行可不要
        servletResponse.setContentType("text/html;charset=" + newCharset);
        System.out.println("这是字符过滤器： " + newCharset);
    }

    @Override
    public void destroy() {

    }
}
